//
//  ThirdPay.swift
//  SwiftTest
//
//  Created by appleTwo on 2019/4/17.
//  Copyright © 2019 QiKai. All rights reserved.
//
/*
 商户系统和微信支付系统主要交互说明：
 
 步骤1：用户在商户APP中选择商品，提交订单，选择微信支付。
 
 步骤2：商户后台收到用户支付单，调用微信支付统一下单接口。
 
 步骤3：统一下单接口返回正常的prepay_id，再按签名规范重新生成签名后，将数据传输给APP。参与签名的字段名为appId，partnerId，prepayId，nonceStr，timeStamp，package。注意：package的值格式为Sign=WXPay
 
 步骤4：商户APP调起微信支付。
 
 步骤5：商户后台接收支付通知。
 
 步骤6：商户后台查询支付结果。
 */

import UIKit

protocol ThirdPayDelegate:NSObjectProtocol {
    func sucessAlipay()
    func faileAlipay()
}

class ThirdPay: NSObject {
    enum type {
        case balance
        case weixin
        case alipay
    }
    
    weak var delegate:ThirdPayDelegate?
    //单例
    static let shared = ThirdPay()
    let appScheme = "alipayswifttest" //自己定义的不能重复 千万记住appScheme与URL Schemes一致 (最好用appid)
    let appidWX = ""  //（申请回来的key 或者叫id 也是工程里面的URLScheme）
    override init() {
        super.init()
    }
    //FIXME: - 这里需要参数
    func ThirdPayTopay(type:type){
        if type == .balance {
            
        }
        if type == .weixin {
            let isAllow = self.WXisAllow()
            if isAllow{
                self.WXResent()//微信支付
            }
        }
        if type == .alipay {
            self.AlipayOrderString(orderString: "alipay_sdk=alipay-sdk-java-3.7.4.ALL&app_id=2019041263846492&biz_content=%7B++++%22out_trade_no%22%3A%2220190417175043jStcY%22%2C++++%22total_amount%22%3A%221.00%22%2C++++%22subject%22%3A%22%E5%85%85%E5%80%BC%22%2C++++%22product_code%22%3A%22QUICK_MSECURITY_PAY%22++%7D&charset=utf-8&format=json&method=alipay.trade.app.pay&sign=W4JRPIYHx42blJyIBpbgc0SbJjC%2FIuMTHF4YxVGxdF%2FOnkuMyvh99j%2F99qdUjvNgRBU9bAo0LIfT7DZ39GuH4N9ep58zJg8q9wqj3sxH5VijWNHoTEgIdwoeNDNYabnU%2FhztELu5pNmR6JgGQMW2HaabBC9etol1rfocVIdda55Qk%2FUB9QEOH8HMOf9caUZWV2Ku3mp4GdzEpOMGJ5wbXor4dqIFiW%2BSs2aorObVxSMe0sETsc0ZE%2F0dG9V3VuggBapASngHPVK2nzSZnDg%2F4s%2BymRMSElynYdDXG5PAxoX0CSBgkm%2BFzclJDPUPUhh2Kv1mhsdwXgKbsa2Wwo8BPw%3D%3D&sign_type=RSA2&timestamp=2019-04-17+17%3A50%3A43&version=1.0")
        }
        
    }
    
    
}
extension ThirdPay{
    
    /// 调支付宝
    ///
    /// - Parameter orderString: 后台返回 根据商品信息返回的
    func AlipayOrderString(orderString:String) {
        AlipaySDK.defaultService().payOrder(orderString, fromScheme: appScheme){
            result in
            print("\(String(describing: result?.description))")
        }
        
    }
    func AlipayToPay(url:URL) {
            AlipaySDK.defaultService().processOrder(withPaymentResult: url as URL){
                value in
                let code = value!
                let resultStatus = code["resultStatus"] as!String
                var content = ""
                switch resultStatus {
                case "9000":
                    content = "支付成功"
                case "8000":
                    content = "订单正在处理中"
                case "4000":
                    content = "支付失败"
                case "5000":
                    content = "重复请求"
                case "6001":
                    content = "中途取消"
                case "6002":
                    content = "网络连接出错"
                case "6004":
                    content = "支付结果未知"
                default:
                    content = "支付失败"
                    break
                }
                SVProgressHUD.show(withStatus: content)
                SVProgressHUD.dismiss(withDelay: 0.8)
                //print("支付结果：\(content)")
                if resultStatus == "900"{
                    self.delegate?.sucessAlipay()
                }else{
                    self.delegate?.faileAlipay()
                }
            }
        }
}
extension ThirdPay:WXApiDelegate{
    //微信
    
    //是否允许
    func WXisAllow() -> Bool{
        if WXApi.isWXAppSupport() == false {
            SVProgressHUD.show(withStatus: "您当前手机微信版本过低")
            SVProgressHUD.dismiss(withDelay: 0.8)
            return false
        }
        if  WXApi.isWXAppInstalled() == false {
            SVProgressHUD.show(withStatus: "您当前手机没有安装微信")
            SVProgressHUD.dismiss(withDelay: 0.8)
            return false
        }
        return true
    }
    ///向微信注册
    func resgisteWeixin() {
        WXApi.registerApp(appidWX)
    }
    ///调取微信
    func WXResent() {
        let request = PayReq()
        request.prepayId = ""
        request.partnerId = ""
        request.package = ""
        request.timeStamp = 22
        request.sign = ""
        request.nonceStr = ""
        WXApi.send(request)
    }
    //微信终端向第三方程序发起请求，要求第三方程序响应。第三方程序响应完后必须调用sendRsp返回。在调用sendRsp返回时，会切回到微信终端程序界面。
    func onReq(_ req: BaseReq) {
        
    }
    //如果第三方程序向微信发送了sendReq的请求，那么onResp会被回调。sendReq请求调用后，会切到微信终端程序界面。
    func onResp(_ resp: BaseResp) {
        if resp.isKind(of: PayResp.self)
        {
            print("retcode = \(resp.errCode), retstr = \(resp.errStr)")
            switch resp.errCode
            {
            //  支付成功
            case 0:
                print("支付成功")
            //  支付失败
            default:
                print("支付失败")
            }
        }
    }
    
}
extension ThirdPay{
    //余额
}











